package com.flyone.qybackend.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.flyone.qybackend.common.BaseResponse;
import com.flyone.qybackend.common.ErrorCode;
import com.flyone.qybackend.common.ResultUtils;
import com.flyone.qybackend.exception.BusinessException;
import com.flyone.qybackend.model.dto.postreply.PostReplyAddRequest;
import com.flyone.qybackend.model.entity.PostReply;
import com.flyone.qybackend.model.entity.User;
import com.flyone.qybackend.model.vo.PostReplyUserVO;
import com.flyone.qybackend.model.vo.UserVO;
import com.flyone.qybackend.service.PostReplyService;
import com.flyone.qybackend.service.PostService;
import com.flyone.qybackend.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.xml.transform.Result;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/post_reply")
@Slf4j
public class PostReplyController {

    @Resource
    private PostReplyService postReplyService;

    @Resource
    private PostService postService;

    @Resource
    private UserService userService;

    @PostMapping("/add")
    public BaseResponse<Boolean> addReplyByPostId(@RequestBody PostReplyAddRequest postReplyAddRequest, HttpServletRequest request){
        if (postReplyAddRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        Long userId = loginUser.getId();

        boolean result = postReplyService.savePostReply(postReplyAddRequest, userId);
        return ResultUtils.success(result);
    }
    @GetMapping("/")
    public BaseResponse<List<PostReplyUserVO>> getReplyByPostId(long id, HttpServletRequest request){
        if (id <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        userService.getLoginUser(request);
        QueryWrapper<PostReply> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("postId", id);
        List<PostReply> list = postReplyService.list(queryWrapper);
        List<PostReplyUserVO> resultList = new ArrayList<>();
        list.forEach(item -> {
            PostReplyUserVO postReplyUserVO = new PostReplyUserVO();
            BeanUtils.copyProperties(item, postReplyUserVO);
            Long userId = item.getUserId();
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            postReplyUserVO.setUser(userVO);
            resultList.add(postReplyUserVO);
        });
        return ResultUtils.success(resultList);
    }

}
